package com.tinem.platform.service.network.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.net.url.UrlPath;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tinem.platform.module.pojo.vo.translate.TranslateReq;
import com.tinem.platform.module.pojo.vo.translate.TranslateRes;
import com.tinem.platform.module.starter.jpa.entity.translate.TranslateLanguage;
import com.tinem.platform.module.starter.jpa.repository.translate.TranslateLanguageRepository;
import com.tinem.platform.service.network.config.LanguageMapping;
import com.tinem.platform.service.network.service.TranslateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @program: platform
 * @description: ${description}
 * @author: eden#can
 * @Slogan: 没有所谓失败，除非你不再尝试
 * @date: 2021-11-10 17:32
 **/
@Slf4j
@Service
public class TranslateServiceImpl implements TranslateService {


    @Value("${baidufanyi.app_id}")
    String app_id;
    @Value("${baidufanyi.app_secret}")
    String app_secret;
    @Value("${baidufanyi.url}")
    String url;

    @Resource
    TranslateLanguageRepository translateLanguageRepository;


    @Override
    public TranslateRes getTranslateResult(TranslateReq req,String sha256) {
        log.info("api get chache translate, msg_sha256:{}",sha256);
        Optional<TranslateLanguage> msgLanOptional = translateLanguageRepository.findById(sha256);
        if (!msgLanOptional.isPresent()) {
            return null;
        }
        TranslateLanguage msgLan = msgLanOptional.get();
        TranslateRes translateRes = new TranslateRes();
        BeanUtil.copyProperties(req,translateRes);
        translateRes.setTarMsg(msgLan.getTarMsg());
        log.info("api get chache translate, res:{}",JSONUtil.toJsonStr(translateRes));
        return translateRes;
    }

    @Override
    public TranslateRes getTranslateByBaiduResult(TranslateReq req) {

        TranslateRes translateRes = new TranslateRes();
        BeanUtil.copyProperties(req,translateRes);

        String queryTxt = req.getMsg();
        // 以当前时间戳作为随机数
        String salt = String.valueOf(System.currentTimeMillis());
        // 根据参数生成对应的签名
        String signStr = StrUtil.format("{}{}{}{}", app_id, queryTxt, salt, app_secret);
        String sign = SecureUtil.md5(signStr);

        String tarlan = LanguageMapping.baiduFanyiMapping(req.getTarLan());

        String buildUrl = UrlBuilder.create()
                .of(url)
                .addQuery("q", queryTxt)
                .addQuery("from", "auto")
                .addQuery("to", tarlan)
                .addQuery("appid", app_id)
                .addQuery("salt", salt)
                .addQuery("sign", sign)
                .build();
        log.info("baidu fanyi api req url:{}",buildUrl);
        HttpResponse response = HttpRequest.get(buildUrl).execute();

        log.info("baidu fanyi api res:{}",JSONUtil.toJsonStr(response));
        // 判断调用是否成功
        if (!response.isOk()) {
            log.error("response is not ok!");
            return translateRes;
        }

        String result = response.body();
        if(StrUtil.isBlank(response.body())){
            log.error("response.body is blank!");
            return translateRes;
        }
        JSONObject jsonObject = JSONUtil.parseObj(result);

        // 错误码 仅当出现错误时显示
        if (jsonObject.containsKey("error_code")) {
            log.error("response containsKey error_code:{}",jsonObject.get("error_code"));
            return translateRes;
        }

        JSONArray transResult = jsonObject.getJSONArray("trans_result");

        Map<String,String> map = (Map)transResult.get(0);

        translateRes.setTarMsg(map.get("dst"));
        log.info("baidu fanyi getTranslateByBaiduResult res:{}",JSONUtil.toJsonStr(translateRes));
        return translateRes;
    }

    @Override
    public void saveTranslateResult(TranslateRes translateRes,String sha256) {

        TranslateLanguage translateLanguage = new TranslateLanguage();
        BeanUtil.copyProperties(translateRes,translateLanguage);

        translateLanguage.setId(sha256);
        translateLanguage.setUpdatedTime(new Date());
        translateLanguage.setCreatedTime(new Date());
        log.info("saveTranslateResult,{}",JSONUtil.toJsonStr(translateLanguage));
        translateLanguageRepository.saveAndFlush(translateLanguage);

    }



    public static void main(String[] args) {
        String url = "http://fanyi-api.baidu.com/api/trans/vip/translate";

        String appid = "20190515000298029";
        double salt = (Math.random() * 9 + 1) * 10000;

        String sign0 = appid+"你好"+salt+"zAc8jOeNuhp6JHeo60AI";

        String sign = SecureUtil.md5(sign0);
        System.out.println(sign);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");


        String buildUrl = UrlBuilder.create()
//                .addPath(url)
                .of(url)
                .addQuery("q", "hello")
                .addQuery("from", "auto")
                .addQuery("to", "en")
                .addQuery("appid", appid)
                .addQuery("salt", String.valueOf(salt))
                .addQuery("sign", sign)
                .build();

        System.out.println(buildUrl);

//        String url11 = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=apple&from=en&to=zh&appid=20190515000298029&salt=1435660288&sign=6a2bcabb97cacd169ef8e95b845aa0f6";

//        HttpRequest request = HttpRequest.get(url11);
//        String result = request.execute().body();
//        System.out.println(result);
        // 发送请求

    }
}
